package org.jmc.refmanager.security;

import java.util.Collection;

import javax.annotation.Resource;

import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public final class SecurityHelper {
	public static final String ROLE_USER = "ROLE_USER";
	public static final String ROLE_APPROVER = "ROLE_APPROVER";
	public static final String ROLE_ADMIN = "ROLE_ADMIN";

	@Resource(name = "passwordEncoder")
	private PasswordEncoder passwordEncoder;

	/**
	 * 
	 * @param clearPassword
	 * @return
	 */
	public String encodePassword(String clearPassword) {
		return passwordEncoder.encodePassword(clearPassword, null);
	}
	
	/**
	 * 
	 * @return L'utilisateur connecte
	 */
	public static Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

	/**
	 * 
	 * @return Vide les donnees d'identification
	 */
	public static void clearContext() {
		SecurityContextHolder.clearContext();
	}

	/**
	 * 
	 * @return
	 */
	public static Collection<GrantedAuthority> getRoles() {
		Authentication authentication = getAuthentication();
		if (!authentication.isAuthenticated()) {
			throw new SecurityException("L'utilisateur n'est pas connecté");
		}
		
		return authentication.getAuthorities();
	}

	/**
	 * 
	 * @return <code>true</code> si l'utilisateur connecte est
	 * un approbateur.
	 */
	public static boolean isApprover() {
		return hasRole(ROLE_APPROVER);
	}

	/**
	 * 
	 * @return <code>true</code> si l'utilisateur connecte est
	 * un administrateur.
	 */
	public static boolean isAdministrator() {
		return hasRole(ROLE_ADMIN);
	}

	/**
	 * 
	 * @return <code>true</code> si l'utilisateur connecte est
	 * un utilisateur.
	 */
	public static boolean isUser() {
		return hasRole(ROLE_USER);
	}

	/*
	 * Whether this roles object contains the provided role.
	 * 
	 * @param role
	 *            the role to check
	 * @return true if it contains the role, false otherwise
	 */
	private static boolean hasRole(final String roleName) {
		boolean has = false;
		if (roleName != null) {
			Collection<GrantedAuthority> authz = getRoles();
			for (GrantedAuthority grantedAuthority : authz) {
				String authzName = grantedAuthority.getAuthority();
				if (authzName.equalsIgnoreCase(roleName)) {
					return true;
				}
			}
		}
		
		return has;
	}
}
